
import numpy as np

class DeviceHeterogeneityMetrics:
    """设备异构性量化指标体系"""
    def __init__(self, alpha=0.8, beta=0.9, max_drop_rate=0.15):
        self.alpha = alpha  # 延迟敏感因子
        self.beta = beta    # 通信质量权重
        self.max_drop_rate = max_drop_rate  # 最大容忍丢包率
        
    def compute_capability_coeff(self, actual_speed, peak_speed, task_delay):
        """计算能力差异系数 (式1)"""
        return np.exp(-self.alpha * task_delay * (peak_speed / actual_speed))
    
    def comm_quality_matrix(self, hist_max_bw, norm_bw, drop_rate):
        """通信质量动态评估 (式2)"""
        stability = (norm_bw / hist_max_bw) * (1 - drop_rate / self.max_drop_rate)
        return self.beta * stability
    
    def layer_divergence(self, client_activations, global_activations):
        """层间散度量化 (式3)"""
        kl_divs = []
        for layer in range(len(client_activations)):
            kl_div = np.sum(client_activations[layer] * np.log(
                client_activations[layer] / global_activations[layer] + 1e-10))
            kl_divs.append(kl_div)
        return np.mean(kl_divs)
    
    def integrated_hetero_score(self, capability, comm_quality, divergence, entropy_weights):
        """综合异构评分 (式4)"""
        return entropy_weights[0]*capability + entropy_weights[1]*comm_quality + entropy_weights[2]*divergence
